import * as vscode from 'vscode';
import { LLMFactory } from '../../../core/llm/llmFactory';
import { FuzzTestGenerator } from './FuzzTestGenerator';

/**
 * Fuzz 测试集成处理器
 * 负责协调 Fuzz 测试生成的整个流程
 */
export class FuzzTestIntegrationHandler {
    private llmFactory: LLMFactory;
    private sendToWebview: (messageType: string, data: any) => void;
    private generator: FuzzTestGenerator | null = null;
    private currentDocument: vscode.TextDocument | null = null;

    constructor(
        llmFactory: LLMFactory,
        sendToWebview: (messageType: string, data: any) => void
    ) {
        this.llmFactory = llmFactory;
        this.sendToWebview = sendToWebview;
    }

    /**
     * 处理生成 Fuzz 测试的请求
     */
    public async handleGenerateRequest(data: {
        filePath: string;
        selectedText: string;
        isWholeFile: boolean;
    }): Promise<void> {
        try {
            // 打开文档
            const document = await vscode.workspace.openTextDocument(data.filePath);
            this.currentDocument = document;

            // 创建生成器
            this.generator = new FuzzTestGenerator(
                this.llmFactory,
                (msg) => this.handleGeneratorMessage(msg)
            );

            // 执行完整的五步生成流程
            await this.generator.executeFullWorkflow(document, data.selectedText, data.isWholeFile);

        } catch (error) {
            console.error('[FuzzTest Integration] 生成失败:', error);
            this.sendToWebview('fuzzError', {
                error: String(error)
            });
        }
    }

    /**
     * 处理生成器发来的消息
     */
    private handleGeneratorMessage(msg: any): void {
        switch (msg.type) {
            case 'info':
                this.sendToWebview('fuzzInfo', {
                    message: msg.content,
                    filePath: msg.filePath
                });
                break;

            case 'warning':
                this.sendToWebview('fuzzWarning', {
                    message: msg.content
                });
                break;

            case 'error':
                this.sendToWebview('fuzzError', {
                    error: msg.content
                });
                break;

            case 'progress':
                this.sendToWebview('fuzzProgress', {
                    message: msg.content
                });
                break;

            case 'text-chunk':
                this.sendToWebview('fuzzTextChunk', {
                    content: msg.content
                });
                break;

            case 'file-created':
                this.sendToWebview('fuzzFileCreated', {
                    message: msg.content,
                    filePath: msg.filePath
                });
                break;

            case 'success':
                this.sendToWebview('fuzzComplete', {
                    message: msg.content,
                    filePath: msg.filePath
                });
                break;

            default:
                console.warn('[FuzzTest Integration] Unknown message type:', msg.type);
        }
    }

    /**
     * 打开文件
     */
    public async openFile(filePath: string): Promise<void> {
        try {
            const uri = vscode.Uri.file(filePath);
            const document = await vscode.workspace.openTextDocument(uri);
            await vscode.window.showTextDocument(document);
        } catch (error) {
            vscode.window.showErrorMessage(`无法打开文件：${error}`);
        }
    }

    /**
     * 暂停当前生成操作
     */
    public pauseCurrentOperation(): void {
        if (this.generator) {
            this.generator.pauseCurrentOperation();
        }
    }

    /**
     * 继续当前生成操作
     */
    public resumeCurrentOperation(): void {
        if (this.generator) {
            this.generator.resumeCurrentOperation();
        }
    }

    /**
     * 取消当前生成操作
     */
    public cancelCurrentOperation(): void {
        if (this.generator) {
            this.generator.cancelCurrentOperation();
        }
    }

    /**
     * 获取当前操作状态
     */
    public getCurrentState(): { isRunning: boolean; isPaused: boolean } {
        if (this.generator) {
            return this.generator.getCurrentState();
        }
        return { isRunning: false, isPaused: false };
    }
}

